﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using OrganizedIN.DAL;
using OrganizedIN.BAL;
using OrganizedIN.BussinessServices;
using System.Data.SqlClient;
using Microsoft.ApplicationBlocks.Data;
using OrganizedIN.BAL.Common;

namespace OrganizedIN.UI.Videos
{
    public partial class M_add_new_videos : System.Web.UI.Page
    {
        DataSet ds = new DataSet();
        string user;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                user = Convert.ToString(Session["UserID"]);
                if (!IsPostBack)
                {
                    //get photo album
                    ds = Common.getVideoAlbum(user);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ListItem li = new ListItem(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
                            drpAlbum.Items.Add(li);
                        }
                    }
                }

                dropDownVideoOption.SelectedIndexChanged += new System.EventHandler(dropDownVideoOption_SelectedIndexChanged);
                txtFileUpload.Visible = true;
                txtEmbedURL.Visible = false;
                lblUserID.Text = Convert.ToString(Session["UserID"]);
                if (IsPostBack && drpAlbum.SelectedItem.ToString() == "+Create Album")
                {
                    pnlAddAlbum.Visible = true;
                }
                else
                {
                    pnlAddAlbum.Visible = false;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string strFinalFilePath = "";
                bool writeData = false;
                SqlService objservices = new SqlService();
                MyProfileVideo objAddNewVideos = new MyProfileVideo();
                //MyProfilePhoto objMyPhoto = new MyProfilePhoto();

                /* 
                * @Author:     Shrikant Meena
                * @Purpose:    Transcodes video using FFMPEG, Creates a snapshot
                * @Date:       11 April 2010 
                */

                string strFilename = string.Empty, strExt = string.Empty;
                string strAppPath = Request.PhysicalApplicationPath;
                string strUploadPath = strAppPath + "\\UploadedVideos\\";
                string strFinalRelPath = "";

                if (dropDownVideoOption.SelectedValue.ToString()=="V")
                {
                    strFilename = txtFileUpload.FileName.ToString();
                    if (txtFileUpload.HasFile)
                    {
                        strExt = System.IO.Path.GetExtension(strFilename);
                        if (strExt == ".wmv" || strExt == ".avi" || strExt == ".mpg" || strExt == ".mpeg" || strExt == ".mp4" || strExt == ".flv")
                        {
                            string strTmpFilename = "tmp_video_" + DateTime.Now.ToString("hhmmss") + strExt;
                            string strTmpUploadPath = strUploadPath + strTmpFilename;
                            string strFinalSnapPath = strUploadPath + "USER_VIDEO_" + Convert.ToString(Session["UserID"]) + DateTime.Now.ToString("hhmmss") + ".jpg";
                            string videoFileName = "USER_VIDEO_" + Convert.ToString(Session["UserID"]) + DateTime.Now.ToString("hhmmss") + ".flv";
                            strFinalFilePath = strUploadPath + videoFileName;
                            strFinalRelPath = "../../UploadedVideos/" + videoFileName;

                            // Actually upload the original file to a temporary path
                            txtFileUpload.PostedFile.SaveAs(strTmpUploadPath);

                            //strUploadPath = @"C:\Inetpub\wwwroot\Organizedin_project\OrganizedIN\UploadedVideos\" + System.IO.Path.GetFileNameWithoutExtension(strFilename) + DateTime.Now.ToString("hhmm") + strExt;
                            //strUploadPath = @Server.MapPath("~") + @"UploadedVideos\" + System.IO.Path.GetFileNameWithoutExtension(strFilename) + DateTime.Now.ToString("hhmm") + strExt;

                            // This is where our FFMPEG & FLVMDI binary resides
                            string strFFMPEG = strAppPath + "\\ffmpeg\\ffmpeg.exe";
                            string strFLVMDI = strAppPath + "\\ffmpeg\\flvmdi.exe";

                            // Arguments to FFMPEG process
                            string fileargsTranscode = " -i " + strTmpUploadPath + " -ar 22050 -ab 32 -f flv -vcodec flv -s 320x240 " + strFinalFilePath;
                            string fileargsSnap = " -y -i " + strTmpUploadPath + " -ss 00:00:07 -f image2 -s 100x60 " + strFinalSnapPath;
                            string fileargsMdiTool = " /k /l " + strFinalFilePath;

                            // Creating a new process to take SNAP from video
                            Process videoSnap = new Process();
                            videoSnap.StartInfo.Arguments = fileargsSnap;
                            videoSnap.StartInfo.FileName = strFFMPEG;
                            videoSnap.StartInfo.UseShellExecute = false;
                            videoSnap.StartInfo.CreateNoWindow = true;
                            videoSnap.StartInfo.RedirectStandardOutput = false;
                            videoSnap.Start();
                            videoSnap = null;

                            // Creating a new process to TRANSCODE video
                            Process transCode = new Process();
                            transCode.StartInfo.Arguments = fileargsTranscode;
                            transCode.StartInfo.FileName = strFFMPEG;
                            transCode.StartInfo.UseShellExecute = false;
                            transCode.StartInfo.CreateNoWindow = true;
                            transCode.StartInfo.RedirectStandardOutput = false;
                            transCode.Start();
                            transCode.WaitForExit();
                            transCode = null;

                            // Embedding Video MetaData
                            Process embeddMetaData = new Process();
                            embeddMetaData.StartInfo.Arguments = fileargsMdiTool;
                            embeddMetaData.StartInfo.FileName = strFLVMDI;
                            embeddMetaData.StartInfo.UseShellExecute = false;
                            embeddMetaData.StartInfo.CreateNoWindow = true;
                            embeddMetaData.StartInfo.RedirectStandardOutput = false;
                            embeddMetaData.Start();
                            embeddMetaData.WaitForExit();
                            embeddMetaData = null;

                            // Deleting temp video file
                            File.Delete(strTmpUploadPath);
                            writeData = true;
                        }
                        else
                        {
                            lblStatus.ForeColor = Color.Red;
                            lblStatus.Text = "Only upload wmv,avi,mpg,mp4 or flv kind of files";
                        }
                    }
                    else
                    {
                        lblStatus.ForeColor = Color.Red;
                        lblStatus.Text = "Please select a file";
                    }
                }
                else
                {
                    strFilename = txtEmbedURL.Text.ToString();
                    int idx = strFilename.IndexOf("www.youtube.com");
                    if (idx == -1)
                    {
                        lblStatus.Text = "Only youtube video embedding is allowed";
                    }
                    else
                    {
                        string[] uParts = strFilename.Split('?');
                        uParts = uParts[1].Split('=');
                        strFilename = "http://www.youtube-nocookie.com/v/" + uParts[1] + "?fs=1&amp;hl=en_US";
                        strFinalRelPath = strFilename;
                        writeData = true;
                    }
                }
                try
                {
                    if (writeData)
                    {
                        objAddNewVideos.VideoSummary = txtVideoSummary.Text;
                        objAddNewVideos.VideoRating = ddlRating.SelectedValue.ToString();
                        objAddNewVideos.VideoSharerName = txtShare.Text;
                        objAddNewVideos.VideoUpload = strFinalRelPath;
                        objAddNewVideos.VideoEventName = txtAddEvent.Text;
                        objAddNewVideos.Album = drpAlbum.Text;
                        objAddNewVideos.VideoTitle = txttitle.Text;

                        //Common.Add_New_Photo(UserName, objMyPhoto.PhotoSummary, objMyPhoto.PhotoUpload, objMyPhoto.PhotoRating, objMyPhoto.PhotoEventName, objMyPhoto.PhotoCreateDate);

                        Common.Add_New_Videos(lblUserID.Text, objAddNewVideos.VideoSummary, objAddNewVideos.VideoRating, objAddNewVideos.VideoSharerName, objAddNewVideos.VideoUpload, objAddNewVideos.VideoEventName, objAddNewVideos.VideoTitle, objAddNewVideos.Album);

                        // Add the video to the album
                        // Commom.Add_Video_Album(params)

                        lblStatus.ForeColor = Color.Green;
                        lblStatus.Text = "Video Uploaded/Embedded Successfully !";
                    }
                }
                catch (Exception ex)
                {
                    lblStatus.ForeColor = Color.Red;
                    lblStatus.Text = "Error Uploading Video !";
                    //throw ex;
                }
                //drpA.Text = "";
                txtEmbedURL.Text = "";
                txtAddEvent.Text = "";
                txtShare.Text = "";
                txtVideoSummary.Text = "";
                txttitle.Text = "";
                ddlRating.SelectedValue = "0";
                dropDownVideoOption.SelectedValue = "V";
                drpAlbum.SelectedValue = "";
            }
            catch (Exception ex)
            {
                lblStatus.ForeColor = Color.Red;
                lblStatus.Text = "Error Uploading Video !";
                //throw ex;
            }
        }

        protected void dropDownVideoOption_SelectedIndexChanged(object sender, EventArgs e)
        {
            string v = dropDownVideoOption.SelectedValue.ToString();
            switch (v)
            {
                case "U":
                    txtFileUpload.Visible = true;
                    txtEmbedURL.Visible = false;
                    break;
                case "E":
                    txtFileUpload.Visible = false;
                    txtEmbedURL.Visible = true;
                    break;
                default:
                    txtFileUpload.Visible = true;
                    txtEmbedURL.Visible = false;
                    break;
            }
        }

        protected void btnCancelAddAlbum_Click(object sender, EventArgs e)
        {
            pnlAddAlbum.Visible = false;
            drpAlbum.SelectedIndex = 0;
        }

        protected void btnCreateAlbum_Click(object sender, EventArgs e)
        {
            try
            {
                ds = Common.getVideoAlbumName(user, txtNewAlbum.Text);
                if (ds.Tables[0].Rows[0][0].ToString() == "0")
                {
                    ds = Common.addVideoAlbum(user, txtNewAlbum.Text);
                    lblalbummsg.ForeColor = Color.Green;
                    lblalbummsg.Text = "Album successfully created";
                    drpAlbum.SelectedIndex = 0;
                    pnlAddAlbum.Visible = false;
                    ds = Common.getVideoAlbum(user, txtNewAlbum.Text);
                    if (ds.Tables[0].Rows.Count > 0)
                    {
                        for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                        {
                            ListItem li = new ListItem(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
                            drpAlbum.Items.Add(li);
                        }
                    }
                }
                else
                {
                    lblalbummsg.Text = "Album already exist";
                }
            }
            catch (Exception ex)
            {
                lblStatus.Text = "There is some error";
            }
        }
    }
}
